#include "Thread.h"
#include <stdio.h>

//on linux, pthread_kill was not declared if sginal.h not included
//while this header file is unecessary on Mac OS
#include <signal.h>

namespace qy
{

void * Thread::_start(void *arg)
{
    Thread *pThread = reinterpret_cast<Thread*>(arg);
	pThread->m_isRunning = true;
	int result = pThread->run();
	pThread->afterRun();
	pThread->m_isRunning = false;
	pThread->m_threadId = 0;
	return (void*)result;
}

Thread::Thread()
{
    m_overCond = NULL;
    m_isRunning = false;
	m_threadId = 0;
}

Thread::~Thread()
{
    if(m_threadId)
	{
	    pthread_kill(m_threadId, 9);
		m_threadId = 0;
	}
}

bool Thread::start()
{
    if(m_threadId)
	{
	    return false;
	}

    int r = pthread_create(&m_threadId, NULL, _start, this);
	if(r != 0)
	{
	    printf("pthread_create error %d\n", r);
		return false;
	}
	return true;
}

void Thread::afterRun()
{
    if(m_overCond)
	{
	    pthread_cond_broadcast(m_overCond);
    }
}

bool Thread::terminate()
{
    if(m_threadId)
	{
	    pthread_kill(m_threadId, 9);
		m_isRunning = false;
		m_threadId = 0;
	}
}

}
